﻿using FireChat.Share.Logger;
using System.Reflection;

namespace FireChat.Share.Command;


/// <summary>
/// 指令映射
/// </summary>
public class CommandMap<T> where T : new()
{
    /// <summary>
    /// 所有指令处理进程
    /// </summary>
    private readonly List<(CommandToken, MethodInfo)> _comamndProcess = new();

    private readonly T _instance = new();

    public CommandMap()
    {
        _comamndProcess.AddRange(CommandScaffold.GetCommands<T>());
    }

    /// <summary>
    /// 执行指令
    /// </summary>
    public object? Invoke(string cmd)
    {
        try
        {
            var tokens = cmd.Split(' ', StringSplitOptions.RemoveEmptyEntries);
            if (tokens.Length < 1) return null;

            var method_info = _comamndProcess.Find(x => x.Item1.IsExists(tokens[0])).Item2;
            if (method_info == null) return null;

            return method_info.Invoke(_instance, tokens[1..]);
        }
        catch (Exception ex)
        {
            ex.LogToConsole();
            return null;
        }
    }
}
